/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package rukopisyimport.foxml;

import cz.mzk.kramerius.imports.FoxmlHelper;
import cz.mzk.kramerius.imports.Datastream;
import cz.mzk.kramerius.imports.DatastreamFactory;
import cz.mzk.kramerius.imports.Policy;
import cz.mzk.kramerius.imports.ReferenceType;
import cz.mzk.kramerius.imports.ReferencedManagedDs;
import cz.mzk.rehan.commons.DatastreamId;
import cz.mzk.rehan.commons.Dom4jUtils;
import org.dom4j.Document;
import rukopisyimport.foxml.images.ImageDownloader;
import rukopisyimport.foxml.images.PreviewGenerator;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dom4j.Node;
import org.dom4j.XPath;
import rukopisyimport.sourceData.MarcDocument;
import rukopisyimport.sourceData.TeiDocument;

/**
 *
 * @author Martin Řehánek (rehan at mzk.cz)
 */
public class ClassicLinkPageBuilder extends AbstractPageBuilder {

    private static final Logger logger = Logger.getLogger(ClassicLinkPageBuilder.class.getName());
    private final PreviewGenerator previewGenerator;
    private final ImageDownloader imageDownloader;
    private final String[] QUALITY_PREFICIES = {"excellent", "Excellent", "/excellent", "priloha/excellent/"};
    private final static boolean clearPicturesDir = false;

    public ClassicLinkPageBuilder(Properties properties) {
        previewGenerator = new PreviewGenerator(properties);
        imageDownloader = new ImageDownloader(properties, clearPicturesDir);
    }

    void createDatastreams(File conversionDir, Page page, Node surfaceNode, MarcDocument marc, TeiDocument tei) throws Exception {
        Datastream dc = createDcDatastream(page);
        page.addDatastream(dc);
        Datastream mods = createModsDatastream(page);
        page.addDatastream(mods);
        Datastream relsExt = createRelsExtDatastream(page, Policy.PUBLIC);
        page.addDatastream(relsExt);
        String imageUrl = getImageUrl(surfaceNode, tei.findUrlBase());
        File originalImage = downloadOriginalImage(imageUrl);
        Datastream imgFull = createImgFullDatastream(imageUrl);
        page.addDatastream(imgFull);
        Datastream imgThumb = createImgThumbDatastream(originalImage);
        page.addDatastream(imgThumb);
        Datastream policy = FoxmlHelper.createPolicyDatastream(Policy.PUBLIC);
        page.addDatastream(policy);
        FoxmlHelper.saveFoxml(conversionDir, page);
    }

    private Datastream createRelsExtDatastream(Page page, Policy policy) {
        Document doc = FoxmlHelper.createRelsExtSkeleton(page, "page", policy);
        return DatastreamFactory.createInlineDatastream(doc, DatastreamId.RELS_EXT);
    }

    private File downloadOriginalImage(String imageUrl) {
        File originalFile = null;
        try {
            originalFile = imageDownloader.downloadAndSaveFile(imageUrl);
        } catch (MalformedURLException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
        return originalFile;
    }

    private String getImageUrl(Node surfaceNode, String urlBase) {
        XPath xpath = Dom4jUtils.createXPath("./tei:graphic/@url");
        List<Node> urlSuffixes = xpath.selectNodes(surfaceNode);
        for (Node urlSuffix : urlSuffixes) {
            String urlSuffixStr = urlSuffix.getText();
            for (String qualityPrefix : QUALITY_PREFICIES) {
                if (urlSuffixStr.startsWith(qualityPrefix)) {
                    return urlBase.concat(urlSuffixStr);
                }
            }
        }
        return null;
    }

    private Datastream createImgFullDatastream(String imageUrl) {
        return DatastreamFactory.createExternalyReferencedDs(imageUrl, DatastreamId.IMG_FULL);
    }

    private Datastream createImgThumbDatastream(File originalImageFile) throws Exception {
        File previewFile = previewGenerator.generatePreview(originalImageFile);
        String url = "file:" + previewFile.getAbsolutePath();
        return new ReferencedManagedDs(ReferenceType.URL, url, DatastreamId.IMG_THUMB, "label", null, "image/jpg");
    }
}
